﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;
using System.IO;
using System.Text;


namespace IMT
{

    /// <summary>
    /// Author: Elliott Perry 01/09/2011
    /// 
    /// This is the child class for SubmitEndorsement messages for Lime Street. It inherits from the base XMLMessage class.
    /// </summary>
    class SubmitEndorsementMSG : XMLMessage
    {

        public XmlDocument XML;
        public XmlDeclaration XMLDec;
        public MessageData MSG;
        

        /// <summary>
        /// Main Constructor that is called from MainWindow.cs and passes the document for path for reading
        /// </summary>
        public SubmitEndorsementMSG(string docPath)
        {
            Debug.WriteLine("DEBUG: Submit Endorsement MSG Object Created: Path = " + docPath + " at " + DateTime.Now.ToString("yyyy MM dd hh mm ss"));

             //Create a MessageData Object;
            MSG = new MessageData();

            disectMessage(docPath);

        }


        /// <summary>
        /// TEST Constructor 
        /// </summary>
        public SubmitEndorsementMSG(string SenderIdentification,
                                string AuthenticationToken,
                                string Operation,
                                string SourceEnvironment,
                                string BrokerID,
                                string BrokerContactName,
                                string BrokerContactTelephone,
                                string BrokerContactEmail,
                                string InsurerReinsurerName,
                                string UMR,
                                string Narrative,
                                string MasterType,
                                string ClassOfBusiness,
                                string CoverType,
                                string BrokerEndorsementReference,
                                string BrokerEndorsementName,
                                string GuaIndicator,
                                string VersionNumber,
                                string[,] PName //Participants array
                                )
        {

            //Create a MessageData Object;
            MSG = new MessageData();

            //Populate Data
            MSG.SenderIdentification = SenderIdentification;
            MSG.AuthenticationToken = AuthenticationToken;
            MSG.Operation = Operation;
            MSG.SourceEnvironment = SourceEnvironment;
            MSG.BrokerID = BrokerID;
            MSG.BrokerContactName = BrokerContactName;
            MSG.BrokerContactTelephone = BrokerContactTelephone;
            MSG.BrokerContactEmail = BrokerContactEmail;
            MSG.InsurerReinsurerName = InsurerReinsurerName;
            MSG.UMR = UMR;
            MSG.Narrative = Narrative;
            MSG.MasterType = MasterType;
            MSG.ClassOfBusiness = ClassOfBusiness;
            MSG.CoverType = CoverType;
            MSG.BrokerEndorsementReference = BrokerEndorsementReference;
            MSG.BrokerEndorsementName = BrokerEndorsementName;
            MSG.GuaIndicator = GuaIndicator;
            MSG.VersionNumber = VersionNumber;
            MSG.PName = PName;

            //Begin to build the Lime-Street Formatted XML 
            buildXMLString(MSG);
           
        }


        /// <summary>
        /// This method builds the XML Message and places this into a string
        /// </summary>
        private void buildXMLString(MessageData Msg)
        {
            XML = new XmlDocument();
            
            XMLDec = XML.CreateXmlDeclaration("1.0", null, null);

            XmlElement root = XML.DocumentElement;
            XML.InsertBefore(XMLDec, root);

            XmlElement PackageEL = (XmlElement)XML.AppendChild(XML.CreateElement("Package"));
            XmlElement SecurityEL = (XmlElement)PackageEL.AppendChild(XML.CreateElement("Security"));

            XmlElement SenderIdentEL = (XmlElement)SecurityEL.AppendChild(XML.CreateElement("SenderIdentification"));
            SenderIdentEL.InnerText = Msg.SenderIdentification;
            XmlElement AuthTokenEL = (XmlElement)SecurityEL.AppendChild(XML.CreateElement("AuthenticationToken"));
            AuthTokenEL.InnerText = Msg.AuthenticationToken;

            XmlElement WorkFlowEL = (XmlElement)PackageEL.AppendChild(XML.CreateElement("Workflow"));

            XmlElement OperationEL = (XmlElement)WorkFlowEL.AppendChild(XML.CreateElement("Operation"));
            OperationEL.InnerText = Msg.Operation;

            XmlElement SourceEnvEL = (XmlElement)WorkFlowEL.AppendChild(XML.CreateElement("SourceEnvironment"));
            SourceEnvEL.InnerText = Msg.SourceEnvironment;

            XmlElement EndorsementEL = (XmlElement)PackageEL.AppendChild(XML.CreateElement("Endorsement"));

            XmlElement BrokerIDEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("BrokerId"));
            BrokerIDEL.InnerText = Msg.BrokerID;

            XmlElement BrokerContNameEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("BrokerContactName"));
            BrokerContNameEL.InnerText = Msg.BrokerContactName;

            XmlElement BrokerContTelEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("BrokerContactTelephone"));
            BrokerContTelEL.InnerText = Msg.BrokerContactTelephone;

            XmlElement BrokerContEmEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("BrokerContactEmail"));
            BrokerContEmEL.InnerText = Msg.BrokerContactEmail;

            XmlElement InsurerReNameEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("InsurerReinsurerName"));
            InsurerReNameEL.InnerText = Msg.InsurerReinsurerName;

            XmlElement UMREL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("UMR"));
            UMREL.InnerText = Msg.UMR;

            XmlElement NarrEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("Narrative"));
            NarrEL.InnerText = Msg.Narrative;

            XmlElement MasterTypeEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("MasterType"));
            MasterTypeEL.InnerText = Msg.MasterType;

            XmlElement CobEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("ClassOfBusiness"));
            CobEL.InnerText = Msg.ClassOfBusiness;

            XmlElement CoverTypeEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("CoverType"));
            CoverTypeEL.InnerText = Msg.CoverType;

            XmlElement BrokerEndRefEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("BrokerEndorsementReference"));
            BrokerEndRefEL.InnerText = Msg.BrokerEndorsementReference;

            XmlElement BrokerEndNameEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("BrokerEndorsementName"));
            BrokerEndNameEL.InnerText = Msg.BrokerEndorsementName;

            XmlElement GuaEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("GuaIndicator"));
            GuaEL.InnerText = Msg.GuaIndicator;

            XmlElement VersionNoEL = (XmlElement)EndorsementEL.AppendChild(XML.CreateElement("VersionNumber"));
            VersionNoEL.InnerText = Msg.VersionNumber;

            XmlElement MarketEL = (XmlElement)PackageEL.AppendChild(XML.CreateElement("Market"));


            /////This loops around to insert the info for the underwriters.
            for (int i = 0; i < Msg.getNumberOfMarkets(); i++)
            {
                //create a Participant Element
                XmlElement ParticipantEL = (XmlElement)MarketEL.AppendChild(XML.CreateElement("Patricipant"));

                //Create child elements. HACK, this is reading from Array, should really make Market Objects and keep them in list.
                XmlElement CarrierNameEL = (XmlElement)ParticipantEL.AppendChild(XML.CreateElement("CarrierName"));
                CarrierNameEL.InnerText = Msg.PName[i, 0];

                XmlElement CarrierConPerEL = (XmlElement)ParticipantEL.AppendChild(XML.CreateElement("CarrierContactPerson"));
                CarrierConPerEL.InnerText = Msg.PName[i, 1];

                XmlElement CarrierConEmailEL = (XmlElement)ParticipantEL.AppendChild(XML.CreateElement("CarrierContactEmail"));
                CarrierConEmailEL.InnerText = Msg.PName[i, 2];


                /////////TO-DO//////////
                //This element creates the agency for the market. Need validation in here for if the Agency is blank i.e PName[i,3] == Null
                XmlElement CarrierIdentEL = (XmlElement)ParticipantEL.AppendChild(XML.CreateElement("CarrierIdentification"));
                CarrierIdentEL.SetAttribute("agency", Msg.PName[i, 3]);
                CarrierIdentEL.InnerText = Msg.PName[i, 4];
                //create 13 elements
                /////////////////////////


                XmlElement ContRefEL = (XmlElement)ParticipantEL.AppendChild(XML.CreateElement("ContractReference"));
                ContRefEL.InnerText = Msg.PName[i, 8];

                XmlElement PartFucnEL = (XmlElement)ParticipantEL.AppendChild(XML.CreateElement("ParticipantFunction"));
                PartFucnEL.InnerText = Msg.PName[i, 9];
            }

            Debug.WriteLine("DEBUG: " + XML.OuterXml.ToString());

            saveXML(XML.OuterXml.ToString());
        }


        /// <summary>
        /// This method should take the path from the constructor, break down the message and append it to the MessageData object
        /// </summary>
        private void disectMessage(string docPath)
        {
            //get delimiter from Global Data
            string delimiter = GlobalData.MessageDelimiter;
            List<string> data = new List<string>();
            

            //Open up FileStream to Doc
            try
            {
                using (StreamReader reader = new StreamReader(docPath))
                {
                    //This string object
                    StringBuilder inputString = new System.Text.StringBuilder();
                    List<string> lstStartBody = new List<string>();
                    bool foundENDBODY = false;
                    int numOfMarkets;
                    
                    //Read lines from document until EoF, 
                    //while(reader.Peek() != null)
                    //{

                        
                        //Read past the SUBMITENDORSEMENT,STARTBODY,
                        for(int i = 0; i < 28; i++)
                            reader.Read();  


                        //This will read in the data for the STARTBODY area and put in a list
                        while (foundENDBODY == false)
                        {

                            //get the next Word i.e. until it finds a tab
                            while (reader.Peek() != GlobalData.MessageDelimiterASCII)
                            {
                                inputString.Append(char.ConvertFromUtf32(reader.Read()));
                            }

                            //check that it is not at end of body section and append to list
                            //Debug.WriteLine("Comparing " + inputString.ToString() + " to ENDBODY");

                            if (inputString.ToString() == "ENDBODY")
                            {
                                Debug.WriteLine("DEBUG: Found ENDBODY of Input Message. ");
                                foundENDBODY = true;
                                inputString.Clear();
                            }
                            else
                            {
                                
                                //Put this into a list
                                lstStartBody.Add(inputString.ToString());

                                //Debug.WriteLine("DATAFOUND: " + inputString.ToString());

                                //read the tab character
                                reader.Read();

                                //clear the inputString object
                                inputString.Clear();
                            }
                        
                        }


                        //Now get Underwriter Information
                        Debug.WriteLine("DEBUG: Getting Underwriter Information");
                        
                        //Read past STARTMARKET,
                        for (int i = 0; i < 13; i++)
                            reader.Read();

                        //Get Number of Markets
                        while (reader.Peek() != GlobalData.MessageDelimiterASCII)
                        {
                            inputString.Append(char.ConvertFromUtf32(reader.Read()));
                            Debug.WriteLine(inputString.ToString());
                        }

                        
                        try
                        {
                            numOfMarkets = Convert.ToInt16(inputString);
                            Debug.WriteLine("NOM = " + numOfMarkets);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("ERROR: Error determining number of markets :" + inputString);

                        }
                    
                        //Append this data into the MessageData object;
                        Debug.WriteLine("DEBUG: Now appending data to MSG Object");

                        //MSG.SenderIdentification = lstStartBody[1];
                        //MSG.AuthenticationToken = lstStartBody[2];
                        //MSG.Operation = lstStartBody[3];
                        //MSG.SourceEnvironment = lstStartBody[4];
                        //MSG.BrokerID = lstStartBody[5];
                        //MSG.BrokerContactName = lstStartBody[6];
                        //MSG.BrokerContactTelephone = lstStartBody[7];
                        //MSG.BrokerContactEmail = lstStartBody[8];
                        //MSG.InsurerReinsurerName = lstStartBody[9];
                        //MSG.UMR = lstStartBody[10];
                        //MSG.Narrative = lstStartBody[11];
                        //MSG.MasterType = lstStartBody[12];
                        //MSG.ClassOfBusiness = lstStartBody[13];
                        //MSG.CoverType = lstStartBody[14];
                        //MSG.BrokerEndorsementReference = lstStartBody[15];
                        //MSG.BrokerEndorsementName = lstStartBody[16];
                        //MSG.GuaIndicator = lstStartBody[17];
                        //MSG.VersionNumber = lstStartBody[18];
                        //MSG.PName = ;




                    //}
                    
                    //string nextCharacter = char.ConvertFromUtf32(reader.Peek());
                    
                   
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("ERROR: Error Opening File in disectMessage: " + e);
            }

            //First line is doc name so ignore

            //Check that next line is STARTBODY & ignore

            //Next line and for each tab read into MSG object
        }

        /// <summary>
        /// This method will take the document objects, called the convertTo64 method and insert them into the correct part of the message
        /// </summary>
        public void insertDocuments()
        {

        }

    }
}
